import { getChanlvConfigApi, getPassengersApi, getPassengerTypeConfApi } from '../../api/index'
import { buildForm, compareForm  } from '../../utils/changlv'
import { channel, SHIP_CERT_TYPE, SHIP_PASSENGER_TYPE, SHIP_PASSENGER_TYPE_BEIHAI, TRACER_PAGES, PRODUCT_CODE } from '../../utils/constants'
import { STORAGE_KEY } from '../../utils/storage'
import { ticketTypeBuilder, checkBeiHaiTicket } from '../booking/main'
import { setPage, queryString } from '../../utils/index'
const pageName = TRACER_PAGES['passengers']
Page({

  /**
   * 页面的初始数据
   */
  data: {
    query: {},
    passengers: [],
    shipCertType: SHIP_CERT_TYPE,
    shipPassengerType: SHIP_PASSENGER_TYPE,
    settings: {},

    showTicketPicker: false,
    passengerTypeConf: {},
    pickerPassenger: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      query: options
    })
    this.init(options)
  },

  onShow: function() {
    setPage(pageName, PRODUCT_CODE)
  },

  init: function(query) {
    const that = this
    const { lineId, supplierId, selectedIds } = query
    that.getChanglvConfig({
      LineId: lineId,
      SupplierId: supplierId
    })
  },
  
  getChanglvConfig: function(startLine) {
    const that = this
    const {LineId, SupplierId} = startLine
    wx.showLoading({
      title: '正在加载...',
      mask: true,
      success: (result)=>{
        
      },
      fail: ()=>{},
      complete: ()=>{}
    });
    getChanlvConfigApi({ LineId }).then(response => {
      const formItems = buildForm(false, response, SupplierId, {})
      that.setData({
        settings: response
      })
      that.getPassengerTypeConf(startLine)
      that.getPassengers(response, startLine, null).then(passengers => {
        wx.hideLoading();
      })
    })
  },

  _currentPassenger: function(data, editForm) {
    let passengerCreate = null
    if(!editForm) return null
    data.forEach(item => {
      const hasCert = item.listNos.filter(cert => cert.certNo === editForm.firstCertNo)
      if(item.linkerName === editForm.linkerName && hasCert.length > 0) {
        passengerCreate = item
      }
    })

    return passengerCreate
  },

  getPassengers: function(settings, startLine, createP) {
    const that = this
    const { SupplierId  } = startLine
    let query = this.data.query
    let { 
      selectedIds,
      limit,
      ticketLeft
    } = query
    const openId = wx.getStorageSync(STORAGE_KEY.openId)
    const unionId = wx.getStorageSync(STORAGE_KEY.unionId)
    const memberId = wx.getStorageSync(STORAGE_KEY.memberId)
    

    

    return getPassengersApi({
      TCMemberId: memberId,
      OpenId: openId,
      UnionId: unionId,
      Channel: channel,
      PageIndex: 1,
      PageSize: 999,
      ShipMemberId: ''
    }).then(response => {
      if(!response || response.length <= 0) {
        that.setData({
          passengers: [],
          selectCount: 0
        })
        return
      }
      let passengers = []
      response.forEach(item => {
        const { passenger, invalidMsg } = compareForm(item, settings, SupplierId, false)

        passengers.push(passenger)
      })

      let passengerCreate = that._currentPassenger(passengers, createP)

      // 已选常旅是否超过上限  乘客上限或者是余票不足
      if(passengerCreate) {
        const selectedCount = selectedIds? selectedIds.split('|').length: 0
        if(selectedCount < limit && selectedCount < ticketLeft) {
          selectedIds += `|${passengerCreate.id}-${passengerCreate.linkerType}`
        }
      }

      passengers.forEach((item, index) => {
        
        if(passengerCreate && item.id === passengerCreate.id) {
          item.linkerType = passengerCreate.linkerType
        } else {
          item.linkerType = 0
        }
        const _idsAndType = selectedIds && selectedIds.split('|')
        if(_idsAndType) {
          _idsAndType.forEach(idType => {
            if(idType.includes(item.id)) {
              const type = idType.split('-')[1]
              item.linkerType = type
            }
          })
        }
        item.isSelected = selectedIds.includes(item.id)
        
      })
      wx.setStorageSync(STORAGE_KEY.selectedIds, selectedIds)
      query.selectedIds = selectedIds
      const selectedPassengers = passengers.filter(item => item.isSelected)
      that.setData({
        query,
        passengers,
        selectCount: selectedPassengers.length
      })

      return passengers
    })
  },

  

  getPassengerTypeConf: function({LineId}) {
    const that = this
    return getPassengerTypeConfApi({LineId}).then(response => {
      that.setData({
        passengerTypeConf: response
      })
      return response
    })
  },

  _selectedPasssengers: function(passengers) {
    return passengers.filter(item => item.isSelected)
  },
  
  onChoosePassenger: function(e) {
    const that = this
    const item = e.currentTarget.dataset.item
    const { 
      limit, 
      seatPrice,
      childSeatPrice,
      displayName,
      oldSeatPrice,
      citizenChildSeatPrice,
      citizenSeatPrice,
      ticketLeft,
      supportChild,
      supportOld,
    } = this.data.query
    if(!item.isValid) {
      this.onEditPassenger(e)
      return
    }

    let passengers = this.data.passengers
    

    const selectedPassengers = this._selectedPasssengers(passengers)
    
    if(limit <= selectedPassengers.length && !item.isSelected) {
      wx.showToast({
        title: `最多只能添加${limit}位乘客`,
        icon: 'none'
      })
      return
    }


    const selectedPassengersBefore = this._selectedPasssengers(passengers)
    if(ticketLeft && ticketLeft <= selectedPassengersBefore.length) {
      wx.showToast({
        title: `余票数量不足，当前余票数${ticketLeft}张`,
        icon: 'none'
      })
      return
    }
    
    if(!item.isSelected) {
      const passengerTypeConf = this.data.passengerTypeConf
      const seat = {
        ChildSeatPrice: childSeatPrice,
        DisplayName: displayName,
        OldSeatPrice: oldSeatPrice,
        SeatPrice: seatPrice,
        CitizenChildSeatPrice: citizenChildSeatPrice,
        CitizenSeatPrice: citizenSeatPrice,
        ticketLeft
      }
      const { ticketTypePickerPassengers, ticketTypeChoose, passenger } = ticketTypeBuilder({
        passengerTypeConf,
        seat,
        p: item,
        supportChild: supportChild === '1',
        supportOld: supportOld === '1'
      })
      that.setData({
        ticketTypePickerPassengers
      })

      if (ticketTypeChoose) {
        that.ticketPickerDialogOpen(passenger)
        return;
      }

    }

    passengers.forEach(p => {
      if(p.id === item.id) {
        p.isSelected = !p.isSelected
      }
    })
    
    const selectedPassengersAfter = this._selectedPasssengers(passengers)

    let query = this.data.query
    const selectedIds = selectedPassengersAfter.map(item => `${item.id}-${item.linkerType}`)
    if(selectedIds.length> 0) {
      query.selectedIds = selectedIds.join('|')
    }

    const selectCount = selectedPassengersAfter.length

    this.setData({
      query,
      passengers,
      selectCount
    })
  },

  
  // 票型选择弹框 打开
  ticketPickerDialogOpen(p) {
    this.setData({
        showTicketPicker: true,
        pickerPassenger: p
    })
  },

  closeTicketTypeLayout() {
    this.setData({
      showTicketPicker: false,
  })
  },

  
  onChooseTicketType: function(e) {
    const item = e.detail
    
    let ticketTypePickerPassengers = Object.assign({}, this.data.ticketTypePickerPassengers)
    
    ticketTypePickerPassengers.list.forEach(_item => {
      _item.isSelected = false
      if(item.id === _item.id) {
        _item.isSelected = true
      }
    })
    this.setData({
      ticketTypePickerPassengers
    })

  },

  onConfirmTciketType: function(e) {
    let ticketTypePickerPassengers = Object.assign({}, this.data.ticketTypePickerPassengers)
    const selectedTicketType = ticketTypePickerPassengers.list.filter(item => item.isSelected)[0]
    if(!selectedTicketType) {
      return
    }
    const passengers = this.data.passengers

    const { passenger } = ticketTypePickerPassengers

    // const currentSeat = this.data.currentSeat
    const { 
      limit, 
      childSeatPrice,
      displayName,
      oldSeatPrice,
      citizenChildSeatPrice,
      citizenSeatPrice,
      ticketLeft,
      supportChild,
      supportOld,

      lineId,
      supplierId,
      voyageCabinId,
    } = this.data.query


    // 北海市民 校验
    const isBeiHai = [0, 1, 22, 24].includes(selectedTicketType.type) && (citizenSeatPrice > 0 || citizenChildSeatPrice > 0)
    if(isBeiHai) {
      checkBeiHaiTicket({
        BelongType: SHIP_PASSENGER_TYPE_BEIHAI[selectedTicketType.type], // (1:岛民,2:市民,3:员工票,4:市民儿童,5:普通成人,6:普通儿童)
        SupplierId: supplierId,
        CertNo: passenger.id? passenger.validFirstCert.certNo: passenger.firstCertNo,
        PassengerName: passenger.linkerName,
        CarryChildCertNo: passenger.carryChildCert || '',
        VoyageCabinId: voyageCabinId || 1,
        LineId: lineId,
      }, passenger.linkerType).then(response => {
        if(response) {
          this.changeTicketType(passengers, passenger, selectedTicketType)
        }
      })
      
      return
    }



    this.changeTicketType(passengers, passenger, selectedTicketType)
  },

  changeTicketType: function(passengers, passenger, selectedTicketType) {
    const that = this

    const { 
      supportChild,
      supportCarry
    } = this.data.query

    const SupportChildTicket = supportChild === '1'
    const SupportCarryChild = supportCarry === '1'
    passengers.forEach(item => {
      if(item.id === passenger.id) {
        item.linkerType = selectedTicketType.type
        item.isSelected = !item.isSelected
        item.supportChild = SupportChildTicket
        item.supportCarryChild = SupportCarryChild && ![1, 24].includes(item.linkerType)
      }
    })
    const selectedPassengers = passengers.filter(item => item.isSelected)

    this.closeTicketTypeLayout()
    this.setData({
      passengers,
      selectCount: selectedPassengers.length
    })
  },

  onConfirm: function() {
    if(this.data.selectCount <= 0) {
      wx.showToast({
        title: `请选择出行乘客！`,
        icon: 'none'
      })
      return
    }
    const passengers = this.data.passengers

    wx.removeStorageSync(STORAGE_KEY.selectedIds)
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('selectPassengersChannel', { data: passengers });

    wx.navigateBack({
      delta: 1
    });
  },

  onGoCreate: function() {
    const that = this
    const query = this.data.query
    const { lineId, supplierId } = query
    const settings = this.data.settings

    query.editId = ''

    const _query = queryString(query)

    wx.navigateTo({
      url: `../create/index?${_query}`,
      events: {
        createPassengerChannel: function({data}) {
          that.getPassengers(settings, {
            LineId: lineId,
            SupplierId: supplierId
          }, data)
        }
      }
    })
  },

  onEditPassenger: function(e) {
    const that = this
    let query = this.data.query
    const { lineId, supplierId } = query
    const settings = this.data.settings
    const editPassenger = e.currentTarget.dataset.item
    // 保存要编辑的常旅到 storage 
    wx.setStorageSync(STORAGE_KEY.editPassenger, editPassenger);

    query.editId = editPassenger.id

    const _query = queryString(query)
    wx.navigateTo({
      url: `../create/index?${_query}`,
      events: {
        createPassengerChannel: function({data}) {
          that.getPassengers(settings, {
            LineId: lineId,
            SupplierId: supplierId
          }, data)
        }
      }
    })
  }
})